<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>智能车机后台配置界面 - 车辆状态</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="container">
    <div class="sidebar">
      <ul>
        <li><a href="index.html">主页</a></li>
        <li><a href="car.html">车辆状态</a></li>
        <li><a href="gps.html">导航设置</a></li>
        <li><a href="audio_control.html">车内监控</a></li>
      </ul>
    </div>
    <div class="content">
      <div class="vehicle-status-grid">
        <div class="grid-item" style="grid-column: 1 / span 1; grid-row: 1 / span 1;">
          <h3>空调温度控制</h3>
          <p>通过滑动滑块调节空调温度</p>
          <input type="range" class="temperature-slider" min="16" max="40" value="25"
            oninput="updateTemperature(this.value)">
          <span id="temperature-display">25°C</span>
        </div>
        <div class="grid-item" style="grid-column: 2 / span 1; grid-row: 1 / span 1;">
          <h3>风速控制</h3>
          <p>通过滑动滑块调节风速</p>
          <input type="range" class="wind-slider" min="0" max="3" step="1" value="0"
            oninput="updateWindSpeed(this.value)">
          <span id="wind-speed-display">0</span>档
        </div>
        <div class="grid-item" style="grid-column: 3 / span 1; grid-row: 1 / span 1;">
          <h3>温湿度检测</h3>
          <p>温度：<span class="temperature-value-box" id="temp"></span>℃</p>
          <p>湿度：<span class="humidity-value-box" id="hum"></span>%</p>
          <button class="refresh-button" onclick="refreshTemperatureHumidity()">刷新</button>
        </div>
        <div class="grid-item" style="grid-column: 1 / span 1; grid-row: 2 / span 1;">
          <h3>寻车功能</h3>
          <p>点击按钮发送寻车命令</p>
          <button class="find-car-button" onclick="sendFindCarCommand()">寻车</button>
        </div>
        <div class="grid-item" style="grid-column: 2 / span 1; grid-row: 2 / span 1;">
          <h3>车门控制</h3>
          <p id="door-status">当前车门状态：关闭</p>
          <button class="door-control-button" onclick="toggleDoor()">切换车门状态</button>
        </div>
        <div class="grid-item" style="grid-column: 3 / span 1; grid-row: 2 / span 1;">
          <h3>雨刷器控制</h3>
          <p id="wiper-status">当前雨刷器状态：关闭</p>
          <button class="wiper-control-button" onclick="toggleWiper()">切换雨刷器状态</button>
        </div>
        <div class="grid-item" style="grid-column: 1 / span 1; grid-row: 3 / span 1;">
          <h3>天窗控制</h3>
          <p id="sunroof-status">当前天窗状态：关闭</p>
          <button class="sunroof-control-button" onclick="toggleSunroof()">切换天窗状态</button>
        </div>
        <div class="grid-item" style="grid-column: 2 / span 1; grid-row: 3 / span 1;">
          <h3>远近光灯控制</h3>
          <p id="light-status">当前灯光状态：关闭</p>
          <button class="light-control-button" onclick="toggleLight()">切换灯光状态</button>
        </div>
        <div class="grid-item" style="grid-column: 3 / span 1; grid-row: 3 / span 1;">
          <h3>电量显示</h3>
          <p>电量：<span class="battery-display" id="level">80%</span></p>
          <button class="battery-refresh-button" onclick="refreshBattery()">刷新</button>
        </div>
      </div>
    </div>
  </div>
  <script>
    var xhr = new XMLHttpRequest();
    // 更新空调温度显示的函数
    function updateTemperature(value) {
      // 获取页面中 id 为 'temperature-display' 的元素，并将滑动条的值与单位 '°C' 拼接后设置为该元素的文本内容
      document.getElementById('temperature-display').innerText = value + '°C';
    }

    //处理风速
    function updateWindSpeed(value) {
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("POST", url, true);
      let displayText;
      switch (value) {
        case '0':
          displayText = '0';
          console.log("wind-off");
          xhr.send("{\"dev\":\"stm32\",\"name\":\"fan\",\"val\":0}");
          break;
        case '1':
          displayText = '1';
          console.log("wind-on1");
          xhr.send("{\"dev\":\"stm32\",\"name\":\"fan\",\"val\":1}");
          break;
        case '2':
          displayText = '2';
          console.log("wind-on2");
          xhr.send("{\"dev\":\"stm32\",\"name\":\"fan\",\"val\":2}");
          break;
        case '3':
          displayText = '3';
          console.log("wind-on3");
          xhr.send("{\"dev\":\"stm32\",\"name\":\"fan\",\"val\":3}");
          break;
      }
      document.getElementById('wind-speed-display').innerText = displayText;
      // 添加错误处理
      xhr.onerror = function () {
        console.error('Request failed');
      };
      return false;
    }

    //寻车功能
    function sendFindCarCommand() {
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("POST", url, true);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            var response = xhr.responseText;
            console.log(response);
            alert('寻车命令已发送');
          } else {
            console.error('寻车命令发送失败');
            alert('寻车命令发送失败，请稍后重试。');
          }
        }
      };
      xhr.send("{\"dev\":\"stm32\",\"name\":\"buzzer\",\"val\":1}");
      return false;
    }

    //处理车门的函数
    function toggleDoor(obj) {
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("POST", url, true);
      let doorStatusElement = document.getElementById('door-status');
      let newStatus;
      if (doorStatusElement.innerText === '当前车门状态：关闭') {
        newStatus = 'open';
        doorStatusElement.innerText = '当前车门状态：开启';
        console.log("door-on");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"door\",\"val\":1}")
      } else {
        newStatus = 'close';
        doorStatusElement.innerText = '当前车门状态：关闭';
        console.log("door-off");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"door\",\"val\":0}")
      }
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            const response = xhr.responseText;
            console.log(response);
          } else {
            console.error('Door status update failed, status code:', xhr.status);
          }
        }
      }
    }

    //处理雨刷器的函数
    function toggleWiper() {
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("post", url, true);
      let wiperStatusElement = document.getElementById('wiper-status');
      let newStatus;
      if (wiperStatusElement.innerText === '当前雨刷器状态：关闭') {
        newStatus = 'open';
        wiperStatusElement.innerText = '当前雨刷器状态：开启';
        console.log("wiper-on");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"wiper\",\"val\":1}");
      } else {
        newStatus = 'close';
        wiperStatusElement.innerText = '当前雨刷器状态：关闭';
        console.log("wiper-off");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"wiper\",\"val\":0}");
      }
      // 当请求状态发生变化时执行的回调函数
      xhr.onreadystatechange = function () {
        // 如果请求已完成（readyState === 4）且状态码为 200（表示成功）
        if (xhr.readyState === 4 && xhr.status === 200) {
          // 获取服务器返回的响应文本
          var response = xhr.responseText;
          // 这里可以根据服务器返回的内容进行相应处理，例如显示成功消息或其他提示
          console.log(response);
        } else if (xhr.readyState === 4) {
          // 如果请求完成但状态码不是 200，说明发生错误
          console.error('Wiper status update failed, status code:', xhr.status);
        }
      };
    }

    //处理天窗的函数
    function toggleSunroof() {
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("post", url, true);
      let sunroofStatusElement = document.getElementById('sunroof-status');
      let newStatus;
      if (sunroofStatusElement.innerText === '当前天窗状态：关闭') {
        newStatus = 'open';
        sunroofStatusElement.innerText = '当前天窗状态：开启';
        console.log("roof-on");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"roof\",\"val\":1}");
      } else {
        newStatus = 'close';
        sunroofStatusElement.innerText = '当前天窗状态：关闭';
        console.log("roof-off");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"roof\",\"val\":0}");
      }
      xhr.onreadystatechange = function () {
        // 如果请求已完成（readyState === 4）且状态码为 200（表示成功）
        if (xhr.readyState === 4 && xhr.status === 200) {
          // 获取服务器返回的响应文本
          var response = xhr.responseText;
          // 这里可以根据服务器返回的内容进行相应处理，比如显示成功消息或其他提示
          console.log(response);
        } else if (xhr.readyState === 4) {
          // 如果请求完成但状态码不是 200，说明发生错误
          console.error('Sunroof status update failed, status code:', xhr.status);
        }
      };
    }

    //处理灯光的函数
    function toggleLight() {
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("post", url, true);
      let lightStatusElement = document.getElementById('light-status');
      let currentStatus = lightStatusElement.innerText;
      let newStatus;
      if (currentStatus === '当前灯光状态：关闭') {
        newStatus = '近光灯';
        lightStatusElement.innerText = '当前灯光状态：近光灯';
        console.log("light-near");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"light\",\"val\":1}");
      } else if (currentStatus === '当前灯光状态：近光灯') {
        newStatus = '远光灯';
        lightStatusElement.innerText = '当前灯光状态：远光灯';
        console.log("light-far");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"light\",\"val\":2}");
      } else {
        newStatus = '关闭';
        lightStatusElement.innerText = '当前灯光状态：关闭';
        console.log("light-off");
        xhr.send("{\"dev\":\"modbus\",\"name\":\"light\",\"val\":0}");
      }
    }

    //刷新获取温湿度
    function refreshTemperatureHumidity() {
      var temperatureElement = document.getElementById('temp');
      var humidityElement = document.getElementById('hum');
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("POST", url, true);
      xhr.onreadystatechange = function () {
        var response = xhr.responseText;
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 先按照";"拆分出温度和湿度数据的两部分
                    var dataParts = response.split(";");

                    // 遍历拆分后的部分，分别处理温度和湿度数据
                    for (var i = 0; i < dataParts.length; i++) {
                        var part = dataParts[i];
                        var tempData = part.split(":");
                        if (tempData.length === 2 && tempData[0] === "temp") {
                            temperatureElement.textContent = tempData[1] + "℃";
                        } else if (tempData.length === 2 && tempData[0] === "hum") {
                            humidityElement.textContent = tempData[1] + "%";
                        }
                    }
                }
            };
            xhr.send(JSON.stringify("getTempHum"));
    }

    //刷新获取电量
    function refreshBattery() {
      var batteryElement = document.getElementById('level');
      var xhr = new XMLHttpRequest();
      var url = "";
      xhr.open("POST", url, true);
      xhr.onreadystatechange = function () {
        var response = xhr.responseText;
        var obj = JSON.parse(response);
        if (xhr.readyState === 4 && xhr.status === 200) {
          batteryElement.textContent = obj.Level + "%";
        }
      };
      xhr.send(JSON.stringify("getLevel"));
    }
  </script>
</body>

</html>